﻿using System;
using System.Collections.Generic;
using System.Linq;
using NetBay.Core.BusinessEntities.Workflow;
using NetBay.Core.BusinessEntities.Workflow.Rules;
using Rio.Framework.Pages.Workflow.Actions;
using Action = NetBay.Core.BusinessEntities.Workflow.Rules.Action;

namespace Rio.Framework.Pages.AppCode.Extensions
{
    public static class WorkflowRulesExtension
    {
        public static WkfState GetCurrentState(this Rules workflowRules, WorkflowInstance instance)
        {
            if (workflowRules == null)
                return null;

            if (instance == null)
                return null;

            if (workflowRules.WkfStates == null)
                return null;

            return workflowRules.WkfStates.Where(rulesState => rulesState.Value == instance.State).SingleOrDefault();
        }

        public static IEnumerable<Action> GetAvailableRulesActions(this WkfState workflowState, bool isSenderOnly)
        {
            return workflowState == null ? 
                null : 
                workflowState.Actions.Where(rulesAction => rulesAction.IsSenderOnly == isSenderOnly);
        }

        public static IEnumerable<WorkflowButtonAction> GetAvailableWorkflowActions(this WkfState workflowState, IEnumerable<WorkflowButtonAction> actions, bool isSenderOnly)
        {
            if (workflowState == null)
                return null;

            if (actions == null)
                return null;

            var rulesActions = workflowState.GetAvailableRulesActions(isSenderOnly);

            if (rulesActions == null)
                return null;

            return from rulesAction in rulesActions from workflowButtonAction in actions where workflowButtonAction.RulesAction == rulesAction select workflowButtonAction;
        }
    }
}
